﻿using System;
using System.Collections.Generic;
using System.Linq;
using QASPRibbon.Controls;

namespace QASPRibbon.Commands
{
    /// <summary>
    /// Helper class for Ribbon commands managing and collecting
    /// </summary>
    internal class RibbonCommandRepository
    {
        readonly List<RibbonCommand> _commands = new List<RibbonCommand>();

        public int GetCommandsCount()
        {
            return _commands.Count;
        }

        public IEnumerable<RibbonCommand> GetCommands()
        {
            return _commands.AsReadOnly();
        }

        public void ClearCommands()
        {
            if (_commands.Count == 0)
                return;
            _commands.Clear();
        }

        public void AddCommands(RibbonElement definition)
        {
            IEnumerable<RibbonControl> controls;

            if (definition is RibbonContextualGroup) controls = ((RibbonContextualGroup)definition).Tabs.SelectMany(t => t.Groups).SelectMany(g => g.AllControls).ToArray();
            else if (definition is RibbonTab) controls = ((RibbonTab)definition).AllControls.ToArray();
            else if (definition is RibbonGroup) controls = ((RibbonGroup)definition).AllControls.ToArray();
            else if (definition is RibbonControl) controls = new[] { (RibbonControl)definition };
            else throw new ArgumentException();

            // MRUSplitButtonDefinition: Command="{Id}MenuCommand"
            //_commands.AddRange(
            //    controls
            //    .OfType<RibbonMRUSplitButton>()
            //    .Select(c =>
            //        new RibbonCommand(
            //            c.FullId + "MenuCommand",
            //            "handleCommand(properties['CommandValueId']);",
            //            "true"
            //            )
            //        ).ToArray()
            //    );


            _commands.AddRange(
                controls.Where(x => x.ClientCommands != null).SelectMany(b => b.ClientCommands.Where(cc => cc != null)));
        }
    }
}
